import { Ref, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import messageTips from '@/components/messageTips'
import DeskStorageManager from '@/utils/deskStorage'
import { useRouter } from 'vue-router'
export interface SelectedRow {
    // 订单内的菜品记录ID（部分场景可能没有）
    id?: number
    // 是否赠送：1 赠送，0 非赠送
    is_present: number
    // 是否等叫：1 等叫，0 非等叫
    is_wait: number
    // 单菜折扣（1-10，10 表示不打折）
    discount: number
    // 是否使用了单菜折扣（与全单折扣区分）
    isUseSingleFoodDiscount: boolean
    // 做法ID集合（选择的做法）
    making_ids: number[]
    // 手写做法集合
    write_making: any[]
    // 当前行绑定的SKU ID
    food_sku_id: number
    // SKU 名称（可选，展示用）
    food_sku_name: string
    // SKU 单价（可选，展示/计算用）
    food_sku_price: number
    // SKU 单位（如 份、例）
    food_sku_unit: string
    // SKU 数量（可选）
    food_sku_num: number
    // 菜品展示名称（可能拼接规格名）
    foodName?: string
    // 套餐/组合菜名（可选）
    foodGroupName?: string
    // 展示单位（与SKU单位一致或来源后台）
    foodUnit?: string
    // 点菜份数
    foodNum: number
    // 单价（用于计算总价）
    foodPrice: number
    // 总价（= 数量 * 单价 * 折扣）
    foodTotalPrice: number
    // 补充描述（口味/做法等拼接）
    foodDescName?: string
    // 打印标记：1 打印，0 不打印
    print?: number

    // wait_time
    wait_time?: string

    // 状态
    status?: number

    edit_price?: number
    // 透传原始菜品数据（包含 skuList 等）
    [key: string]: any
}

export function useSelectedActions(options: {
    selectedListState: Ref<SelectedRow[]>
    activeIndexState: Ref<number>
    activeCountState: Ref<number>
    props?: any
    desktopBelongTypeRef?: any
    emit?: (event: string, ...args: any[]) => void
}) {
    const { selectedListState, activeIndexState, activeCountState, emit } = options

    const router = useRouter()
    // 独立动作函数定义（与 useFoodActions.ts 风格一致）
    const actionDeleteSelected = async (_emit: (e: 'action', idx: number) => void) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) {
            ElMessage.warning('请先选择需要删除的菜品')
            return
        }
        const current = selectedListState.value[activeIndexState.value]
        try {
            const messageInstance: any = await messageTips.message(
                {
                    title: '删除Del',
                    content: `确定删除（${current.foodName || current.foodGroupName || ''}）吗？`,
                    isOnCancel: true,
                    onCancelText: '取消',
                    onSumbitText: '确定删除'
                },
                async () => {
                    try {
                        messageInstance.setLoading(true)
                        const i = activeIndexState.value
                        if (i < 0 || i >= selectedListState.value.length) return
                        selectedListState.value.splice(i, 1)
                        if (selectedListState.value.length === 0) {
                            activeIndexState.value = -1
                            activeCountState.value = 0
                            return
                        }
                        const nextIndex = Math.min(i, selectedListState.value.length - 1)
                        activeIndexState.value = nextIndex
                        activeCountState.value = selectedListState.value[nextIndex].foodNum
                        ElMessage.success('删除成功')
                    } finally {
                        messageInstance.setLoading(false)
                        messageInstance.close && messageInstance.close()
                    }
                },
                async () => { }
            )
        } catch (error) { }
    }

    // 规格/数量 弹框状态与数据（用于 SpecificationQuantityDialog）
    const showSpecQuantityDialog = ref(false)
    const specFoodData = ref<any>(null)
    const specLoading = ref(false)
    const specActionType = ref<'add' | 'edit'>('add')

    // 打开规格/数量弹框：基于当前选中行构造回显（不请求后端）
    const actionOpenSpecQuantity = (_emit?: (e: 'action', idx: number) => void) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) {
            ElMessage.warning('请先选择菜品')
            return
        }
        const sel: any = selectedListState.value[activeIndexState.value]
        const raw: any = sel._raw || {}
        const payload: any = {
            ...raw,
            name: raw.name || sel.foodName,
            image_url: raw.images && raw.images.length ? raw.images[0].file.preview_url : '',
            spec_type: raw.spec_type ?? (Array.isArray(raw.skuList) && raw.skuList.length > 1 ? 20 : 10),
            skuList: raw.skuList || [],
            skuInfo: { food_sku_id: sel.food_sku_id },
            num: sel.foodNum || 1,
            print: sel.print || 1
        }
        specFoodData.value = payload
        specActionType.value = 'edit'

        showSpecQuantityDialog.value = true
    }



    // 全部打印：二次确认并批量设置为打印
    const actionFullPrintOn = async (_emit: (e: 'action', idx: number) => void) => {
        try {
            const messageInstance: any = await messageTips.message(
                {
                    title: '全部打印',
                    content: '确定进行全单打印的操作吗？',
                    isOnCancel: true,
                    onCancelText: '取消',
                    onSumbitText: '确定'
                },
                async () => {
                    try {
                        messageInstance.setLoading(true)
                        selectedListState.value.forEach(row => (row.print = 1))
                        ElMessage.success('已设置为全单打印')
                    } finally {
                        messageInstance.setLoading(false)
                        messageInstance.close && messageInstance.close()
                    }
                },
                async () => { }
            )
        } catch (e) { }
    }

    // 全单不打印：二次确认并批量设置为不打印
    const actionFullPrintOff = async (_emit: (e: 'action', idx: number) => void) => {
        try {
            const messageInstance: any = await messageTips.message(
                {
                    title: '全单不打印',
                    content: '确定进行全单不打印的操作吗？',
                    isOnCancel: true,
                    onCancelText: '取消',
                    onSumbitText: '确定'
                },
                async () => {
                    try {
                        messageInstance.setLoading(true)
                        selectedListState.value.forEach(row => (row.print = 0))
                        ElMessage.success('已设置为全单不打印')
                    } finally {
                        messageInstance.setLoading(false)
                        messageInstance.close && messageInstance.close()
                    }
                },
                async () => { }
            )
        } catch (e) { }
    }

    // 全部撤增：二次确认并批量撤销赠送状态
    const actionFullRevokeGift = async (_emit: (e: 'action', idx: number) => void) => {
        try {
            const messageInstance: any = await messageTips.message(
                {
                    title: '全部撤增',
                    content: '确定撤销所有菜品的赠送状态吗？',
                    isOnCancel: true,
                    onCancelText: '取消',
                    onSumbitText: '确定'
                },
                async () => {
                    try {
                        messageInstance.setLoading(true)
                        selectedListState.value.forEach(row => {
                            row.is_present = 0 // 撤销赠送状态
                            delete row.gift_reason // 清除赠送原因
                        })
                        ElMessage.success('已撤销全部赠送')
                    } finally {
                        messageInstance.setLoading(false)
                        messageInstance.close && messageInstance.close()
                    }
                },
                async () => { }
            )
        } catch (e) { }
    }

    // 打开做法面板
    const actionOpenPractice = (emit: any) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]

        // 手写菜品不允许设置做法
        if (sel.is_write_food === 1) {
            ElMessage.warning('手写菜品不支持设置做法')
            return
        }

        // 通过事件通知父组件打开做法面板
        emit('openPractice', sel)
    }

    // 打开口味面板
    const actionOpenTaste = (emit: any) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]
        emit('openTaste', sel)
    }

    // 打开部位面板
    const actionOpenPosition = (emit: any) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]
        emit('openPosition', sel)
    }

    // 打开配菜面板
    const actionOpenSideDish = (emit: any) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]

        // 手写菜品不允许设置配菜
        if (sel.is_write_food === 1) {
            ElMessage.warning('手写菜品不支持设置配菜')
            return
        }

        emit('openSideDish', sel)
    }

    // 检查是否全部赠送
    const isAllGift = () => {
        if (selectedListState.value.length === 0) return false
        return selectedListState.value.every(row => row.is_present === 1)
    }

    // 检查是否全部打印
    const isAllPrint = () => {
        if (selectedListState.value.length === 0) return false
        return selectedListState.value.every(row => row.print === 1)
    }

    // 检查是否全部不打印
    const isAllNoPrint = () => {
        if (selectedListState.value.length === 0) return false
        return selectedListState.value.every(row => row.print === 0)
    }

    // 检查打印状态（用于判断是否显示打印按钮）
    const hasPrintStatus = () => {
        if (selectedListState.value.length === 0) return false
        return selectedListState.value.some(row => row.print !== undefined && row.print !== null)
    }

    // 右侧按钮定义（动态计算，根据状态显示不同按钮）
    const actionsList = computed(() => {
        // 获取当前选中的菜品
        const currentFood = activeIndexState.value >= 0 && activeIndexState.value < selectedListState.value.length
            ? selectedListState.value[activeIndexState.value]
            : null
        const isHandwriteFood = currentFood && currentFood.is_write_food === 1

        const baseActions = [
            { name: '规格/数量', needSelectFood: true, fun: actionOpenSpecQuantity },
            { name: '删除Del', needSelectFood: true, fun: actionDeleteSelected },
            { name: '改价', needSelectFood: true, fun: () => (showPrePriceDialog.value = true) },

            {
                name: '做法',
                needSelectFood: true,
                fun: actionOpenPractice,
                disabled: isHandwriteFood // 手写菜品禁用做法按钮
            },
            { name: '口味', needSelectFood: true, fun: actionOpenTaste },
            { name: '部位', needSelectFood: true, fun: actionOpenPosition },
            {
                name: '配菜',
                needSelectFood: true,
                fun: actionOpenSideDish,
                disabled: isHandwriteFood // 手写菜品禁用配菜按钮
            }
        ]

        // 根据赠送状态动态添加赠送/撤增按钮
        if (isAllGift()) {
            baseActions.push({ name: '全部撤增', needSelectFood: false, fun: actionFullRevokeGift })
        } else {
            baseActions.push({ name: '全部赠送', needSelectFood: false, fun: () => (showPreGiftDialog.value = true) })
        }

        // 根据打印状态动态添加打印按钮
        if (hasPrintStatus()) {
            if (isAllPrint()) {
                baseActions.push({ name: '全单不打印', needSelectFood: false, fun: actionFullPrintOff })
            } else if (isAllNoPrint()) {
                baseActions.push({ name: '全部打印', needSelectFood: false, fun: actionFullPrintOn })
            } else {
                // 混合状态，显示两个按钮
                baseActions.push({ name: '全部打印', needSelectFood: false, fun: actionFullPrintOn })
                baseActions.push({ name: '全单不打印', needSelectFood: false, fun: actionFullPrintOff })
            }
        } else {
            // 没有设置过打印状态，默认显示全部打印按钮
            baseActions.push({ name: '全部打印', needSelectFood: false, fun: actionFullPrintOn })
        }

        // 添加其他功能按钮
        baseActions.push(
            { name: '全部打折', needSelectFood: false, fun: () => (showPreDiscountDialog.value = true) },
            { name: '全部等叫', needSelectFood: false, fun: () => (showPreWaitDialog.value = true) },
            { name: '手写菜品', needSelectFood: false, disabled: false, fun: actionHandwritingFood },
        )

        return baseActions
    })

    const handleSelect = (index: number, item: SelectedRow) => {
        activeIndexState.value = index
        activeCountState.value = Number(item.foodNum || 0)
    }

    const handleClearAll = async () => {
        try {
            const messageInstance: any = await messageTips.message(
                {
                    title: '清空已点',
                    content: '确定清空所有已点菜品吗？',
                    isOnCancel: true,
                    onCancelText: '取消',
                    onSumbitText: '确定清空'
                },
                async () => {
                    try {
                        messageInstance.setLoading(true)
                        selectedListState.value = []
                        activeIndexState.value = -1
                        activeCountState.value = 0
                        ElMessage.success('已清空')
                    } finally {
                        messageInstance.setLoading(false)
                        messageInstance.close && messageInstance.close()
                    }
                },
                async () => { }
            )
        } catch (e) {
            // ignore
        }
    }

    const handleBack = async (deskId: string, next) => {
        /* TODO 返回逻辑占位 */
        if (selectedListState.value.length === 0) {
            clearDeskCacheData(deskId)
            next()
            return
        }
        const messageInstance = await messageTips.message(
            {
                title: '温馨提示',
                content: '您确定要取消当前下单的操作吗？<br /> 确定取消点击“确定”，需暂存菜品点击“暂存”',
                isOnCancel: true,
                onCancelText: '暂存',
                onSumbitText: '确定'
            },
            async () => {
                clearDeskCacheData(deskId)
                next()
                messageInstance.close && messageInstance.close()
            },
            async () => {
                // 使用新的暂存管理器保存数据
                if (deskId) {
                    DeskStorageManager.saveDeskData(deskId, {
                        selectedList: selectedListState.value,
                        activeIndex: activeIndexState.value,
                        activeCount: activeCountState.value
                    })
                }
                next()
                messageInstance.close && messageInstance.close()
            },
        )
    }


    const handleCount = (type: 'add' | 'delete') => {
        const idx = activeIndexState.value

        if (idx < 0 || idx >= selectedListState.value.length) return
        const item = selectedListState.value[idx]

        console.log(item._raw.is_weight);

        // 检查是否为重量商品
        const isWeight = item._raw?.is_weight === 1

        if (type === 'add') {
            if (isWeight) {
                // 重量商品支持小数，每次增加0.01kg，支持两位小数
                item.foodNum = Number((Number(item.foodNum || 0) + 0.01).toFixed(2))
            } else {
                // 普通商品整数增加
                item.foodNum = Number(item.foodNum || 0) + 1
            }
        } else {
            if (isWeight) {
                // 重量商品支持小数，每次减少0.01kg，支持两位小数
                item.foodNum = Number((Number(item.foodNum || 0) - 0.01).toFixed(2))
            } else {
                // 普通商品整数减少
                item.foodNum = Number(item.foodNum || 0) - 1
            }

            if (item.foodNum <= 0) {
                selectedListState.value.splice(idx, 1)
                if (selectedListState.value.length === 0) {
                    activeIndexState.value = -1
                    activeCountState.value = 0
                    return
                }
                const nextIndex = Math.min(idx, selectedListState.value.length - 1)
                activeIndexState.value = nextIndex
                activeCountState.value = selectedListState.value[nextIndex].foodNum
                return
            }
        }
        const base = Number(item.foodPrice || 0)
        const discountRate = Number(item.discount || 10) / 10
        item.foodTotalPrice = Number((Number(item.foodNum) * base * discountRate).toFixed(2))
        activeCountState.value = item.foodNum
    }

    const handleActionBar = (
        index: number,
        emit: (e: 'action', idx: number) => void
    ) => {
        const currentAction = actionsList.value[index]

        if (!currentAction) return

        // 检查按钮是否被禁用
        if (currentAction.disabled) {
            return // 禁用状态直接返回，不执行任何操作
        }

        if (currentAction.needSelectFood && (activeIndexState.value === -1 || activeIndexState.value >= selectedListState.value.length)) {
            ElMessage.warning('请先选择菜品')
            return
        }
        if (currentAction.fun) {
            currentAction.fun(emit)
            return
        }
        emit('action', index)
    }

    const addFoodFromMenu = (food: any) => {
        if (!food) return
        if (food.num === 0) {
            ElMessage.warning('菜品已售罄')
            return
        }
        // 判断是否为套餐
        const isPackage = food.is_group === 1 || food.foodgroup_info

        if (isPackage) {
            // 套餐菜品，需要打开套餐选择弹框
            const packageData = {
                ...food,
                foodGroupId: food.skuList[0].foodgroup_id,
                foodGroupName: food.foodgroup_name || food.name,
                food_sku_id: food.food_sku_id || (food.skuList && food.skuList[0] ? food.skuList[0].id : 0),
                price: food.price || (food.skuList && food.skuList[0] ? food.skuList[0].price : 0),
                foodUnit: food.foodUnit || (food.skuList && food.skuList[0] ? food.skuList[0].unit : '份')
            }

            // 触发套餐选择弹框
            if (emit) {
                emit('openPackage', packageData)
            }
            return
        }

        // 判断是否为多规格菜品
        const isMultiSpec = Array.isArray(food.skuList) && food.skuList.length > 1

        if (isMultiSpec) {
            // 多规格菜品，需要打开规格选择弹框
            const payload: any = {
                ...food,
                name: food.name,
                image_url: food.images && food.images.length ? food.images[0].file.preview_url : '',
                spec_type: 20, // 多规格
                skuList: food.skuList || [],
                skuInfo: null, // 需要用户选择
                print: 1,
                num: 1
            }
            specFoodData.value = payload
            specActionType.value = 'add'
            showSpecQuantityDialog.value = true
            return
        }

        // 单规格菜品，直接添加
        const firstSku = Array.isArray(food.skuList) && food.skuList.length ? food.skuList[0] : null
        const foodSkuId = firstSku ? firstSku.id : 0
        let existIndex = selectedListState.value.findIndex(it => (it as any).food_sku_id === foodSkuId)

        if (existIndex === -1) {
            const unit = (firstSku as any)?.unit || (food as any).foodUnit
            const price = Number((firstSku as any)?.price || (food as any).price || 0)
            const item: any = {
                foodName: food.name,
                foodUnit: unit,
                foodDescName: '',
                food_sku_id: foodSkuId,
                foodNum: 1,
                discount: 10,
                isUseSingleFoodDiscount: false,
                foodPrice: price,
                print: 1,
                foodTotalPrice: price,
                _raw: food
            }
            selectedListState.value.push(item)
            existIndex = selectedListState.value.length - 1
        } else {
            const exist: any = selectedListState.value[existIndex]
            exist.foodNum = Number(exist.foodNum || 0) + 1
            const base = Number(exist.foodPrice || 0)
            const discountRate = Number(exist.discount || 10) / 10
            exist.foodTotalPrice = Number((Number(exist.foodNum) * base * discountRate).toFixed(2))
        }
        activeIndexState.value = existIndex
        activeCountState.value = selectedListState.value[existIndex].foodNum
    }

    // 套餐确认处理
    const onPackageConfirm = (packageData: any) => {
        // 检查是否已存在相同的套餐
        let existIndex = selectedListState.value.findIndex((it: any) =>
            it.food_sku_id === packageData.food_sku_id && it.is_group === 1
        )
        if (existIndex === -1) {
            // 新增套餐
            const item: any = {
                foodName: packageData.foodGroupName,
                foodUnit: packageData.foodUnit,
                foodDescName: '',
                food_sku_id: packageData.food_sku_id,
                foodNum: 1,
                discount: 10,
                isUseSingleFoodDiscount: false,
                foodPrice: packageData.foodPrice,
                print: 1,
                foodTotalPrice: packageData.foodTotalPrice,
                is_group: 1, // 标记为套餐
                foodgroup_id: packageData.foodgroup_id,
                foodGroupName: packageData.foodGroupName,
                food_ids: packageData.food_ids,
                foodGroupSelectFoodList: packageData.foodGroupSelectFoodList,
                _raw: packageData
            }
            selectedListState.value.push(item)
            existIndex = selectedListState.value.length - 1
        } else {
            // 增加套餐数量
            const exist: any = selectedListState.value[existIndex]
            exist.foodNum = Number(exist.foodNum || 0) + 1
            const base = Number(exist.foodPrice || 0)
            const discountRate = Number(exist.discount || 10) / 10
            exist.foodTotalPrice = Number((Number(exist.foodNum) * base * discountRate).toFixed(2))
            exist.foodGroupSelectFoodList = packageData.foodGroupSelectFoodList
            exist.food_ids = packageData.food_ids
        }

        activeIndexState.value = existIndex
        activeCountState.value = selectedListState.value[existIndex].foodNum
    }

    // 规格/数量确认：更新本地预下单数据或添加新菜品
    /**
     * 确认规格与数量。
     * 行为由 specActionType 决定：
     * - 'add'：来自菜单新增的多规格选择；若相同 SKU 已存在则合并数量，否则新增为新行。
     * - 'edit'：来自右侧“规格/数量”修改；仅更新当前行，不新增。
     *
     * @param payload.num        数量
     * @param payload.food_sku_id 选择的SKU ID（多规格必传）
     */
    const onSpecConfirm = (payload: { num: number; food_sku_id?: any }) => {
        const selectedSkuId = payload.food_sku_id
        const isFromAdd = specActionType.value === 'add'
        debugger

        // 新增路径：多规格选择，先尝试合并已有SKU，再决定是否新增
        if (isFromAdd && specFoodData.value && selectedSkuId) {
            const matched = specFoodData.value.skuList.find((s: any) => s.food_sku_id === selectedSkuId || s.id === selectedSkuId)
            if (matched) {
                const targetSkuId = matched.id ?? matched.food_sku_id
                const existIdx = selectedListState.value.findIndex(it => (it as any).food_sku_id === targetSkuId)
                if (existIdx !== -1) {
                    const exist: any = selectedListState.value[existIdx]
                    exist.foodNum = Number(exist.foodNum || 0) + Number(payload.num)
                    const base = Number(exist.foodPrice || 0)
                    const discountRate = Number(exist.discount || 10) / 10
                    exist.foodTotalPrice = Number((Number(exist.foodNum) * base * discountRate).toFixed(2))
                    activeIndexState.value = existIdx
                    activeCountState.value = exist.foodNum
                    showSpecQuantityDialog.value = false
                    return
                }
                // 不存在相同SKU，新增为一行（不同规格视为不同菜）
                const skuName = Array.isArray(matched.food_props) && matched.food_props.length && matched.food_props[0]?.value?.name
                    ? matched.food_props[0].value.name
                    : ''
                const newItem: any = {
                    foodName: skuName ? `${specFoodData.value.name}(${skuName})` : specFoodData.value.name,
                    foodUnit: matched.unit || '份',
                    foodDescName: '',
                    food_sku_id: targetSkuId,
                    foodNum: Number(payload.num),
                    discount: 10,
                    isUseSingleFoodDiscount: false,
                    foodPrice: Number(matched.price || 0),
                    print: 1,
                    foodTotalPrice: Number((Number(payload.num) * Number(matched.price || 0)).toFixed(2)),
                    _raw: specFoodData.value
                }
                selectedListState.value.push(newItem)
                activeIndexState.value = selectedListState.value.length - 1
                activeCountState.value = newItem.foodNum
                showSpecQuantityDialog.value = false
                return
            }
        }

        // 修改路径：仅更新当前选中行
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]
        sel.foodNum = Number(payload.num)
        if (selectedSkuId && specFoodData.value && Array.isArray(specFoodData.value.skuList)) {
            const matched = specFoodData.value.skuList.find((s: any) => s.food_sku_id === selectedSkuId || s.id === selectedSkuId)
            if (matched) {
                sel.food_sku_id = matched.id ?? matched.food_sku_id
                sel.foodPrice = Number(matched.price || sel.foodPrice || 0)
                sel.foodUnit = matched.unit || sel.foodUnit
                const skuName = Array.isArray(matched.food_props) && matched.food_props.length && matched.food_props[0]?.value?.name
                    ? matched.food_props[0].value.name
                    : ''
                const baseName = specFoodData.value?.name || sel.foodName
                sel.foodName = skuName ? `${baseName}(${skuName})` : baseName
            }
        }
        const base = Number(sel.foodPrice || 0)
        sel.foodTotalPrice = Number((Number(sel.foodNum) * base).toFixed(2))
        activeCountState.value = sel.foodNum
        showSpecQuantityDialog.value = false
    }

    // 下单前改价弹框
    const showPrePriceDialog = ref(false)
    const onPrePriceConfirm = (payload: { price: number }) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]
        // 给后端的
        sel.edit_price = Number(payload.price)
        sel.foodPrice = Number(payload.price)
        sel.foodTotalPrice = Number((Number(sel.foodNum || 0) * Number(sel.foodPrice || 0)).toFixed(2))
        showPrePriceDialog.value = false
    }

    // 下单前全部等叫弹框
    const showPreWaitDialog = ref(false)
    const onPreWaitConfirm = (payload: { printType: number; waitTime?: string }) => {
        // 批量设置所有已点菜品为等叫状态
        selectedListState.value.forEach((item: any) => {
            item.is_wait = 1 // 设置为等叫
            item.print = payload.printType // 设置打印状态
            item.status = 3 // 设置为等叫
            if (payload.waitTime) {
                item.wait_time = payload.waitTime // 设置等叫时间
            }
        })
        showPreWaitDialog.value = false
        ElMessage.success('已设置为全部等叫')
    }

    // 下单前全部赠送弹框
    const showPreGiftDialog = ref(false)
    const onPreGiftConfirm = (payload: { reason: string }) => {
        // 批量设置所有已点菜品为赠送状态
        selectedListState.value.forEach((item: any) => {
            item.is_present = 1 // 设置为赠送
            item.gift_reason = payload.reason // 设置赠送原因
        })
        showPreGiftDialog.value = false
        ElMessage.success('已设置为全部赠送')
    }

    // 下单前全部打折弹框
    const showPreDiscountDialog = ref(false)
    const onPreDiscountConfirm = (payload: { discount: string; type: 'apply' | 'revoke' }) => {
        // 批量设置所有已点菜品的折扣
        selectedListState.value.forEach((item: any) => {
            if (payload.type === 'apply') {
                item.discount = Number(payload.discount) // 设置折扣值
                item.isUseSingleFoodDiscount = false // 标记为全单打折
            } else if (payload.type === 'revoke') {
                item.discount = 10 // 恢复原价
                item.isUseSingleFoodDiscount = false
            }
            // 重新计算总价
            const base = Number(item.foodPrice || 0)
            const discountRate = Number(item.discount || 10) / 10
            item.foodTotalPrice = Number((Number(item.foodNum || 0) * base * discountRate).toFixed(2))
        })
        showPreDiscountDialog.value = false
        ElMessage.success(payload.type === 'apply' ? '已设置全单打折' : '已撤销全单打折')
    }

    // 更新菜品描述名称的统一函数
    const updateFoodDescName = (sel: any) => {
        const descParts = []

        // 按顺序添加：口味 -> 部位 -> 做法
        if (sel.tasteDesc) {
            descParts.push(sel.tasteDesc)
        }
        if (sel.positionDesc) {
            descParts.push(sel.positionDesc)
        }
        if (sel.practiceDesc) {
            descParts.push(sel.practiceDesc)
        }

        sel.foodDescName = descParts.join('/')
    }

    // 下单前做法面板
    const showPrePracticePanel = ref(false)
    const onPrePracticeConfirm = (payload: { making_ids: number[]; write_making: any[], selectedNames: any[], totalMoney: number }) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]
        sel.making_ids = payload.making_ids
        sel.write_making = payload.write_making
        // 保存做法描述到独立字段
        sel.practiceDesc = Array.isArray(payload.selectedNames) ? payload.selectedNames.join('/') : ''
        // 重新组合所有描述
        updateFoodDescName(sel)
        // 计算金额·1
        sel.foodTotalPrice = (Number(payload.totalMoney) + Number(sel.foodTotalPrice || 0)).toFixed(2)
        showPrePracticePanel.value = false
        ElMessage.success('做法已更新')
    }

    // 下单前口味面板确认
    const onPreTasteConfirm = (payload: { taste_ids: number[]; write_taste: string[]; selectedNames?: string[] }) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]
        sel.taste_ids = Array.isArray(payload.taste_ids) ? payload.taste_ids : []
        sel.write_taste = Array.isArray(payload.write_taste) ? payload.write_taste : []
        // 保存口味描述到独立字段
        sel.tasteDesc = Array.isArray(payload.selectedNames) ? payload.selectedNames.join('/') : ''
        // 重新组合所有描述
        updateFoodDescName(sel)
        ElMessage.success('口味已更新')
    }

    // 下单前部位面板确认
    const onPrePositionConfirm = (payload: { position: string[]; selectedNames?: string[] }) => {
        if (activeIndexState.value < 0 || activeIndexState.value >= selectedListState.value.length) return
        const sel: any = selectedListState.value[activeIndexState.value]
        sel.position = Array.isArray(payload.position) ? payload.position : []
        // 保存部位描述到独立字段
        sel.positionDesc = Array.isArray(payload.selectedNames) ? payload.selectedNames.join('/') : ''
        // 重新组合所有描述
        updateFoodDescName(sel)
        ElMessage.success('部位已更新')
    }

    // 手写菜品相关状态
    const showHandwritingDialog = ref(false)

    // 手写菜品相关函数
    const actionHandwritingFood = () => {
        showHandwritingDialog.value = true
    }

    const onHandwritingFoodConfirm = (handwriteFoodData: any) => {
        // 添加手写菜品到选中列表
        selectedListState.value.push(handwriteFoodData)

        // 更新当前选中索引为最后一个（新添加的菜品）
        activeIndexState.value = selectedListState.value.length - 1
        activeCountState.value = Number(handwriteFoodData.foodNum || 0)

        // 更新当前选中菜品数据
        // const newFood = selectedListState.value[activeIndexState.value]
        // 这里可以触发更新当前选中菜品数据的事件

        ElMessage.success('手写菜品添加成功')
    }


    // 加载桌台暂存数据
    const loadDeskCacheData = (deskId: string) => {
        if (!deskId) return

        const cacheData = DeskStorageManager.loadDeskData(deskId)
        if (cacheData) {
            selectedListState.value = cacheData.selectedList || []
            activeIndexState.value = cacheData.activeIndex || -1
            activeCountState.value = cacheData.activeCount || 0

            console.log(`已加载桌台 ${deskId} 的暂存数据:`, {
                selectedCount: cacheData.selectedList?.length || 0,
                activeIndex: cacheData.activeIndex
            })
        }
    }

    // 清除桌台暂存数据
    const clearDeskCacheData = (deskId: string) => {
        if (deskId) {
            DeskStorageManager.clearDeskData(deskId)
            console.log(`已清除桌台 ${deskId} 的暂存数据`)
        }
    }

    // 下单成功后清除暂存数据
    const onCreateOrAddSuccess = (deskId: string) => {
        clearDeskCacheData(deskId)
    }

    return {
        handleSelect,
        handleClearAll,
        handleBack,
        handleCount,
        handleActionBar,
        addFoodFromMenu,
        onPackageConfirm,
        actionsList,
        // 删除
        actionDeleteSelected,
        // 状态检查函数
        isAllGift,
        isAllPrint,
        isAllNoPrint,
        hasPrintStatus,
        // 规格/数量弹框绑定
        showSpecQuantityDialog,
        specFoodData,
        specLoading,
        onSpecConfirm,
        // 下单前改价弹框绑定
        showPrePriceDialog,
        onPrePriceConfirm,
        // 下单前全部等叫弹框绑定
        showPreWaitDialog,
        onPreWaitConfirm,
        // 下单前全部赠送弹框绑定
        showPreGiftDialog,
        onPreGiftConfirm,
        // 下单前全部打折弹框绑定
        showPreDiscountDialog,
        onPreDiscountConfirm,
        // 下单前做法面板绑定
        showPrePracticePanel,
        onPrePracticeConfirm,
        // 下单前口味面板绑定
        onPreTasteConfirm,
        // 下单前部位面板绑定
        onPrePositionConfirm,
        // 手写菜品相关
        showHandwritingDialog,
        onHandwritingFoodConfirm,
        // 暂存数据管理
        loadDeskCacheData,
        clearDeskCacheData,
        onCreateOrAddSuccess,
    }
}


